import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"
import Reg from "@/views/Reg/Reg"
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import Login from "@/views/Login/Login"
// 1. 导入后台主页组件
import Main from '@/views/Main/Main.vue'
// 1. 导入 Home 组件
import Home from '@/views/Menus/Home/Home.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
// 导入路由组件
import ArtList from '@/views/Menus/Article/ArtList.vue'
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [{
    path: "/reg",
    component: Reg
  }, {
    path: "/login",
    component: Login
  }, // 2. 后台主页的路由规则
  {
    path: '/',
    component: Main,
    redirect: "/home",
    children: [{
        path: "/home",
        component: Home
      },
      // 用户信息的子路由规则
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (to.path === "/login" || to.path === "/reg") {
    next()
  } else {
    if (!token) {
      next("/login")
    } else {
      next()
    }
  }

})

export default router
